import router from '@/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { NO_LOGIN_PATH } from '@/config'
import { getToken } from '@/utils/user'
import { isExternal } from '@/utils/tools/validate'
import { isShowLogin } from '@/utils/request'
import { msgError } from '@/plugins/modal'
import useUserStore from '@/store/modules/user'
import useSettingsStore from '@/store/modules/settings'
import usePermissionStore from '@/store/modules/permission'

NProgress.configure({ showSpinner: false })
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    to.meta.title && useSettingsStore().setTitle(to.meta.title)
    /* has token*/
    if (to.name === 'Login') {
      return next({ name: 'Index' })
    }
    if (NO_LOGIN_PATH.includes(to.path)) {
      return next()
    }
    if (useUserStore().roles.length === 0) {
      isShowLogin.show = true
      // 判断当前用户是否已拉取完user_info信息
      useUserStore()
        .AuthInfo()
        .then(() => {
          isShowLogin.show = false
          usePermissionStore()
            .generateRoutes()
            .then(accessRoutes => {
              // 根据roles权限生成可访问的路由表
              accessRoutes.forEach(route => {
                if (!isExternal(route.path)) {
                  router.addRoute(route) // 动态添加可访问路由表
                }
              })
              next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
            })
        })
        .catch(err => {
          useUserStore()
            .logOut()
            .then(() => {
              msgError(err)
              next({ name: 'Index' })
            })
        })
    } else {
      next()
    }
  } else {
    // 没有token
    if (NO_LOGIN_PATH.includes(to.path)) {
      // 在免登录白名单，直接进入
      next()
    } else {
      // 否则全部重定向到登录页
      next({ name: 'Login', query: { redirect: to.fullPath }, replace: true })
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
